package com.lenovo.smarttraffic.ui.activity.stage4;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;
import com.lenovo.smarttraffic.util.Utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TrafficManageActivity extends BaseActivity {

    private Spinner spinner;
    private Button find_btn, set_btn;

    private RecyclerView recyclerView;

    private List<Map<String, Integer>> data = new ArrayList<>();
    private TrafficManageAdapter adapter;

    //Flag to avoid multiple items bug
    private boolean canFind = true;

    @Override
    protected int getLayout() {
        return R.layout.activity_traffic_manage;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolBar(this, "红绿灯管理");

        spinner = findViewById(R.id.spinner);
        find_btn = findViewById(R.id.find_btn);
        set_btn = findViewById(R.id.set_btn);

        recyclerView = findViewById(R.id.recycler_view);

        initData();
    }

    private void initData() {
        adapter = new TrafficManageAdapter(this, data);
        recyclerView.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                refresh(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        find_btn.setOnClickListener(v -> {
            if (canFind) {
                refresh(spinner.getSelectedItemPosition());
            }
        });

        set_btn.setOnClickListener(v -> {
            boolean hasChecked = false;//Check if has at lest one checkbox is checked
            for (int i = 0; i < TrafficManageAdapter.intArray.size(); i++) {
                if (TrafficManageAdapter.intArray.get(i) == 1) {
                    hasChecked = true;
                    break;
                }
            }
            if (hasChecked) {
                traffic_set(true);
            } else {
                ToastUtils.showToast(TrafficManageActivity.this, "请至少勾选一个操作项");
            }
        });

    }

    public void traffic_set(boolean multi) {
        View view = View.inflate(this, R.layout.dialog_traffic_set, null);
        EditText red_et = view.findViewById(R.id.red_et);
        EditText yellow_et = view.findViewById(R.id.yellow_et);
        EditText green_et = view.findViewById(R.id.green_et);

        new AlertDialog.Builder(this)
                .setTitle("红绿灯设置")
                .setView(view)
                .setPositiveButton("确定", (dialog, which) -> {
                    int red = Utils.parseInt(red_et.getText().toString());
                    int yellow = Utils.parseInt(yellow_et.getText().toString());
                    int green = Utils.parseInt(green_et.getText().toString());

                    if (red < 10 || yellow < 3 || yellow > 5 || green < 10) {
                        ToastUtils.showToast(TrafficManageActivity.this, "请输入正确的值");
                    } else {
                        ProgressDialog progressDialog = new ProgressDialog(TrafficManageActivity.this);
                        progressDialog.setTitle("请求网络中");
                        progressDialog.setMessage("请稍后");
                        progressDialog.setCancelable(false);
                        progressDialog.show();

                        if (TrafficManageAdapter.singlePos > -1 && !multi) {
                            HttpUtils.post("set_trafficlight_config", new HttpUtils().setParam("TrafficLightId", TrafficManageAdapter.singlePos)
                                            .setParam("RedTime", red).setParam("GreenTime", green).setParam("YellowTime", yellow)
                                            .setParam("UserName", MainActivity.userName),
                                    response -> {
                                        if (Utils.getResult(response)) {
                                            ToastUtils.showToast(TrafficManageActivity.this, "路口" + TrafficManageAdapter.singlePos + "设置成功");
                                            refresh(spinner.getSelectedItemPosition());
                                        } else {
                                            ToastUtils.showToast(TrafficManageActivity.this, "网络请求失败");
                                        }
                                    });
                        } else {
                            for (int i = 0; i < TrafficManageAdapter.intArray.size(); i++) {
                                if (TrafficManageAdapter.intArray.get(i) == 1) {//If checked
                                    int finalI = i + 1;
                                    HttpUtils.post("set_trafficlight_config", new HttpUtils().setParam("TrafficLightId", finalI)
                                                    .setParam("RedTime", red).setParam("GreenTime", green).setParam("YellowTime", yellow)
                                                    .setParam("UserName", MainActivity.userName),
                                            response -> {
                                                if (Utils.getResult(response)) {
                                                    ToastUtils.showToast(TrafficManageActivity.this, "路口" + finalI + "设置成功");
                                                    refresh(spinner.getSelectedItemPosition());
                                                } else {
                                                    ToastUtils.showToast(TrafficManageActivity.this, "网络请求失败");
                                                }
                                            });
                                }
                            }
                        }
                        progressDialog.dismiss();
                    }
                }).setNegativeButton("取消", null).show();
    }

    private void refresh(int which) {
        canFind = false;
        //Clear data
        data.clear();
        TrafficManageAdapter.singlePos = -1;
        for (int i = 0; i < TrafficManageAdapter.intArray.size(); i++) {
            TrafficManageAdapter.intArray.put(i, 0);
        }

        for (int i = 1; i <= 5; i++) {
            int finalI = i;
            HttpUtils.post("get_trafficlight_config", new HttpUtils().setParam("TrafficLightId", i).setParam("UserName", MainActivity.userName),
                    resp -> {
                        if (!canFind) {//To avoid multiple items
                            HashMap<String, Integer> values = new HashMap<>();
                            values.put("id", finalI);
                            values.put("red", (int) resp.get("RedTime"));
                            values.put("green", (int) resp.get("GreenTime"));
                            values.put("yellow", (int) resp.get("YellowTime"));
                            data.add(values);
                            if (finalI == 5) {
                                switch (which) {
                                    case 1:
                                        //路口降序
                                        Collections.reverse(data);
                                        break;
                                    case 2:
                                        //红灯升序
                                        Collections.sort(data, (o1, o2) -> o1.get("red") - o2.get("red"));
                                        break;
                                    case 3:
                                        //红灯降序
                                        Collections.sort(data, (o1, o2) -> o2.get("red") - o1.get("red"));
                                        break;
                                    case 4:
                                        //绿灯升序
                                        Collections.sort(data, (o1, o2) -> o1.get("green") - o2.get("green"));
                                        break;
                                    case 5:
                                        //绿灯降序
                                        Collections.sort(data, (o1, o2) -> o2.get("green") - o1.get("green"));
                                        break;
                                    case 6:
                                        //黄灯升序
                                        Collections.sort(data, (o1, o2) -> o1.get("yellow") - o2.get("yellow"));
                                        break;
                                    case 7:
                                        //黄灯降序
                                        Collections.sort(data, (o1, o2) -> o2.get("yellow") - o1.get("yellow"));
                                        break;
                                }
                                adapter.notifyDataSetChanged();
                                canFind = true;
                            }
                        }
                    });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!MainActivity.userName.equals("admin")) {
            ToastUtils.showToast(this, "请使用管理员账户登录");
            finish();
        }
    }

}

class TrafficManageAdapter extends RecyclerView.Adapter<TrafficManageAdapter.ViewHolder> {

    public static SparseIntArray intArray = new SparseIntArray(5);
    public static int singlePos = -1;

    private TrafficManageActivity activity;
    private List<Map<String, Integer>> data;

    TrafficManageAdapter(TrafficManageActivity activity, List<Map<String, Integer>> data) {
        this.activity = activity;
        this.data = data;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_traffic_manage, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.road_tv.setText("" + data.get(position).get("id"));
        holder.red_tv.setText("" + data.get(position).get("red"));
        holder.yellow_tv.setText("" + data.get(position).get("yellow"));
        holder.green_tv.setText("" + data.get(position).get("green"));

        if (intArray.get(position, -1) == -1) {
            intArray.put(position, holder.checkbox.isChecked() ? 1 : 0);
        } else {
            holder.checkbox.setChecked(intArray.get(position) == 1);
        }

        holder.checkbox.setOnCheckedChangeListener((buttonView, isChecked) -> intArray.put(holder.getAdapterPosition(), isChecked ? 1 : 0));

        holder.set_btn.setOnClickListener(v -> {
            singlePos = holder.getAdapterPosition() + 1;
            activity.traffic_set(false);
        });

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView road_tv, red_tv, yellow_tv, green_tv;
        CheckBox checkbox;
        Button set_btn;

        private ViewHolder(View itemView) {
            super(itemView);

            road_tv = itemView.findViewById(R.id.road_tv);
            red_tv = itemView.findViewById(R.id.red_tv);
            yellow_tv = itemView.findViewById(R.id.yellow_tv);
            green_tv = itemView.findViewById(R.id.green_tv);
            checkbox = itemView.findViewById(R.id.checkbox);
            set_btn = itemView.findViewById(R.id.set_btn);
        }
    }
}
